package net.zigin.nhi.waste.view.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guoqi.actionsheet.ActionSheet;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.bean.UserLogoutSuccessEvent;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.utils.BitmapUtils;
import net.zigin.nhi.waste.view.main.LoginActivity;
import net.zigin.nhi.waste.view.widget.ChangePwdDialog;
import net.zigin.nhi.waste.view.widget.DialogManager;

import org.greenrobot.eventbus.EventBus;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import io.paperdb.Paper;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


/**
 * 个人信息界面
 */
public class PersonalActivity extends AppCompatActivity implements ActionSheet.OnActionSheetSelected {

    private RelativeLayout mChangePic;
    private ImageView mHeadPic;
    private TextView mRealName;
    private TextView mHospitalName;
    private TextView mDepartName;
    private TextView mRoleName;
    private RelativeLayout mChangePwd;
    private RelativeLayout mExit;

    private Bitmap changeHeadPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);

        initView();
        initData();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        ImmersionBar.with(this).init();
        mChangePic = findViewById(R.id.changePic);
        mHeadPic = findViewById(R.id.headPic);
        mRealName = findViewById(R.id.realName);
        mHospitalName = findViewById(R.id.hospitalName);
        mDepartName = findViewById(R.id.departName);
        mRoleName = findViewById(R.id.roleName);
        mChangePwd = findViewById(R.id.changePwd);
        mExit = findViewById(R.id.exit);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getUserInfo();
        mChangePwd.setOnClickListener(v -> {
            ChangePwdDialog dialog = new ChangePwdDialog(this);
            dialog.show();
        });

        mExit.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("提示：");
            builder.setMessage("是否退出登录？");
            builder.setCancelable(true);            //点击对话框以外的区域是否让对话框消失

            //设置正面按钮
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Paper.book().delete(Constants.TOKEN);
                    EventBus.getDefault().post(new UserLogoutSuccessEvent());
                    Intent intent = new Intent(PersonalActivity.this, LoginActivity.class);
                    startActivity(intent);
                    dialog.dismiss();
                    finish();
                }
            });
            //设置反面按钮
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        });

        mChangePic.setOnClickListener(v -> {
            ActionSheet.showSheet(PersonalActivity.this, this, null);
        });
    }

    /**
     * 设置个人信息
     */
    private void getUserInfo() {
        String token = Paper.book().read(Constants.TOKEN);
        String id = Paper.book().read(Constants.STAFFID);
        if (token != null && id != null) {
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getStaffInfoById(token, id);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    Log.i("个人信息", data);
                    JSONObject object = JSON.parseObject(data);
                    String realName = object.getString("realName");
                    String roleName = object.getString("roleName");
                    String hospitalName = object.getString("hospitalName");
                    String departName = object.getString("departName");
                    String headPicUrl = object.getString("headPic");
                    if (realName != null) {
                        mRealName.setText(realName);
                    }
                    if (roleName != null) {
                        mRoleName.setText(roleName);
                    }
                    if (hospitalName != null) {
                        mHospitalName.setText(hospitalName);
                    }
                    if (departName != null) {
                        mDepartName.setText(departName);
                    }
                    if (headPicUrl != null) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap = BitmapUtils.urlToBitmap(headPicUrl, PersonalActivity.this);
                                Bitmap roundBitmap = BitmapUtils.toRoundBitmap(bitmap);
                                runOnUiThread(() -> {
                                    mHeadPic.setImageBitmap(roundBitmap);
                                });
                            }
                        }).start();
                    }
                }
            });
        }
    }

    @Override
    public void onClick(int whichButton) {
        switch (whichButton) {
            case ActionSheet.CHOOSE_PICTURE:
                //相册
                choosePic();
                break;
            case ActionSheet.TAKE_PICTURE:
                //拍照
                takePic();
                break;
            case ActionSheet.CANCEL:
                //取消
                break;
        }
    }

    /**
     * 选择本地图片
     */
    private void choosePic() {
        Intent it = new Intent();
        it.setType("image/*");
        it.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(it, 2);
    }

    /**
     * 拍照
     */
    private void takePic() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);
    }

    float scale;

    //为了适应不同屏幕的显示
    public int getPixel(int old) {
        return (int) (old * scale + 0.5f);
    }

    // 对分辨率较大的图片进行缩放
    public Bitmap zoomBitmap(Bitmap bitmap, float width, float height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix matrix = new Matrix();
        float scaleWidth = (width / w);
        float scaleHeight = (height / h);

        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Uri mImageCaptureUri = data.getData();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(getPixel(300), getPixel(250));
            params.setMargins(0, 15, 0, 15);
            if (mImageCaptureUri != null) {
                try {
                    //这个方法是根据Uri获取Bitmap图片的静态方法
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageCaptureUri);
                    // 获取屏幕分辨率
                    DisplayMetrics dm_2 = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm_2);
                    // 图片分辨率与屏幕分辨率比例
                    float scale_2 = bitmap.getWidth() / (float) dm_2.widthPixels;

                    Bitmap newBitMap = null;
                    if (scale_2 > 1) {
                        newBitMap = zoomBitmap(bitmap, bitmap.getWidth() / scale_2, bitmap.getHeight() / scale_2);
                        bitmap.recycle();
                    }

                    changeHeadPic = BitmapUtils.toRoundBitmap(newBitMap);
                    if (changeHeadPic != null) {
                        String basePic = BitmapUtils.bitmapToBase64(changeHeadPic);
                        File file = null;
                        try {
                            file = BitmapUtils.decoderBase64File(basePic, this);
                            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
                            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                                    .uploadHead(Paper.book().read("token").toString(), body);
                            DialogManager.getInstance().showLoading(this);
                            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                                @Override
                                protected void success(String url) {
                                    if (StringUtil.isNotEmpty(url)) {
                                        Log.i("图片地址", url);
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Bitmap bitmap = BitmapUtils.urlToBitmap(url, PersonalActivity.this);
                                                Bitmap roundBitmap = BitmapUtils.toRoundBitmap(bitmap);
                                                runOnUiThread(() -> {
                                                    mHeadPic.setImageBitmap(roundBitmap);
                                                });
                                            }
                                        }).start();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                    Bitmap image = extras.getParcelable("data");
                    if (image != null) {
                        changeHeadPic = BitmapUtils.toRoundBitmap(image);
                        if (changeHeadPic != null) {
                            String basePic = BitmapUtils.bitmapToBase64(changeHeadPic);
                            File file = null;
                            try {
                                file = BitmapUtils.decoderBase64File(basePic, this);
                                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
                                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                                Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                                        .uploadHead(Paper.book().read("token").toString(), body);
                                DialogManager.getInstance().showLoading(this);
                                HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                                    @Override
                                    protected void success(String url) {
                                        if (StringUtil.isNotEmpty(url)) {
                                            Log.i("图片地址", url);
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Bitmap bitmap = BitmapUtils.urlToBitmap(url, PersonalActivity.this);
                                                    Bitmap roundBitmap = BitmapUtils.toRoundBitmap(bitmap);
                                                    runOnUiThread(() -> {
                                                        mHeadPic.setImageBitmap(roundBitmap);
                                                    });
                                                }
                                            }).start();
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

        }
    }
}